﻿using Ndns.ServerHost.Abstractions.Services;
using System;
using System.Collections.Generic;
using System.Collections;

namespace Ndns.ServerHost.Services
{
    class ServiceCollectionImpl : IServiceCollection
    {
        private readonly Dictionary<Type, object> _services;

        public ServiceCollectionImpl()
        {
            _services = new Dictionary<Type, object>();
        }

        public object this[Type key] { get => _services[key]; }

        public TService Get<TService>()
        {
            try
            {
                if (_services.TryGetValue(typeof(TService), out var result))
                {
                    var castedResult = (TService)result;
                    return castedResult;
                }
            }
            catch (Exception)
            {
                // nop
            }
            return default(TService);
        }

        internal void Add(Type serviceType, object serviceObject)
        {
            // TODO 检查类型是否匹配
            if (_services.ContainsKey(serviceType))
            {
                _services[serviceType] = serviceObject;
            }
            else
            {
                _services.Add(serviceType, serviceObject);
            }
        }

        public IEnumerator<KeyValuePair<Type, object>> GetEnumerator()
        {
            return _services.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return _services.GetEnumerator();
        }
    }
}
